/*
 * @Description:  工具类
 * @Author: Myruun
 * @Date: 2021-07-29 09:44:07
 * @LastEditors: Myruun
 * @LastEditTime: 2021-08-27 11:39:51
 * @FilePath: \serve\unit\index.js
 */


exports.getClientIP = (req) => {
  return req.headers['x-forwarded-for'] || // 判断是否有反向代理 IP
    req.headers['x-real-ip']
};

exports.getTree = (
  source = [],
  idField = 'id',
  parentIdField = 'uid',
  childrenField = 'children',
) => {
  // 对源数据深度克隆
  const cloneData = JSON.parse(JSON.stringify(source))
  const tree = cloneData.filter(parent => {
    if (Number(parent[parentIdField]) !== 0) {
      parent = ''
    }
    // 返回每一项的子级数组
    const branchArr = cloneData.filter(child => parent[idField] === Number(child[parentIdField]))
    // 如果存在子级，则给父级添加一个children属性，并赋值，否则赋值为空数组
    if (branchArr.length > 0) {
      parent[childrenField] = branchArr
    }
    return parent // 返回第一层
  })
  return tree
};